package com.dongdongshop.service.impl.content;

import com.dongdongshop.mapper.TbContentMapper;
import com.dongdongshop.pojo.content.TbContent;
import com.dongdongshop.service.content.ContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
@com.alibaba.dubbo.config.annotation.Service

public class ContentServiceImpl implements ContentService {
    @Autowired
    private TbContentMapper tbContentMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Value("$(redisContent.key)")
    private String key;
    @Value("$(redisContent.field)")
    private String field;

    @Override
    public List<TbContent> listContent() {
        return tbContentMapper.selectByExample(null);
    }

    @Override
    public int insertContent(TbContent tbContent) {
        if (tbContent.getStatus() == null){
            tbContent.setStatus("0");
        }
        redisTemplate.delete(key);
        return tbContentMapper.insertSelective(tbContent);
    }

    @Override
    public TbContent getContentById(Long id) {
        return tbContentMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateContentById(TbContent tbContent) {
        redisTemplate.delete(key);
        return tbContentMapper.updateByPrimaryKeySelective(tbContent);
    }

    @Override
    public int deleteContent(Long[] ids) {
        redisTemplate.delete(key);
        return tbContentMapper.deleteContent(ids);
    }

    @Override
    public List<TbContent> listSlideshow(Long categoryId) {
        HashOperations hashJedis = redisTemplate.opsForHash();
        Boolean hasKey = hashJedis.hasKey(key, field + categoryId);
        if (hasKey){
            List<TbContent> contentList = (List<TbContent>) hashJedis.get(key,field+categoryId);
            return contentList;
        }else{
            List<TbContent> tbContentList = tbContentMapper.listSlideshow(categoryId);
            hashJedis.put(key,field+categoryId,tbContentList);
            return tbContentList;
        }

    }
}
